package com.ironmaking.Controller;

import com.ironmaking.Entity.User;
import com.ironmaking.Handler.Security.Security;
import com.ironmaking.Service.impl.LoginService;
import com.ironmaking.Service.impl.UserService;
import com.ironmaking.Utils.converter.ICopy;
import com.ironmaking.Utils.converter.UserConverter;
import com.ironmaking.Vo.data.BaseUser;
import com.ironmaking.Vo.params.LoginParams;
import com.ironmaking.Vo.params.RegisterParams;
import com.ironmaking.Vo.results.ActionResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(value = "/user", tags = "用户相关接口")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    LoginService loginService;

    @PostMapping("/login")
    @ApiOperation(value = "登录", httpMethod = "POST")
    public ActionResult login(@RequestBody LoginParams loginParams){
        return loginService.checkLogin(loginParams);
    }

    @PostMapping("/register")
    @ApiOperation(value = "注册", httpMethod = "POST")
    public ActionResult register(@RequestBody RegisterParams registerParams){
        return loginService.register(registerParams);
    }

    @RequestMapping("/authorize")
    @ApiOperation(value = "在头部加上名为“Authorization”的Token，解析用户信息", httpMethod = "POST")
    public ActionResult authorizeUserByToken(@RequestHeader("Authorization") String token){
        User user = userService.getUserByToken(token);
        if(user == null){
            return ActionResult.fail(401,"未登录用户或用户不存在，请重新登录");
        }
        else return ActionResult.success(UserConverter.toVoUser(user, (ICopy<BaseUser, User>) user1 -> {
            BaseUser baseUser = new BaseUser();
            BeanUtils.copyProperties(user1,baseUser);
            return baseUser;
        }));
    }

    @Security
    @RequestMapping("/userInfo/{uid}")
    @ApiOperation(value = "根据用户id，解析用户信息,需要Token鉴权", httpMethod = "GET")
    public ActionResult getUserInfoById(@RequestHeader("Authorization") String token, @PathVariable("uid") int uid){
        User user = userService.getUserById(uid);
        if(user == null){
            return ActionResult.fail(401,"用户不存在");
        }
        else return ActionResult.success(UserConverter.toVoUser(user, (ICopy<BaseUser, User>) user1 -> {
            BaseUser baseUser = new BaseUser();
            BeanUtils.copyProperties(user1,baseUser);
            return baseUser;
        }));
    }


}
